package com.xiaoyu.lanling.feature.camera

import android.content.Context
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.View
import com.xiaoyu.base.utils.RxUtils
import com.xiaoyu.camera.listener.ClickListener
import com.xiaoyu.camera.listener.JCameraListener
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.event.camera.ImageCaptureEvent
import com.xiaoyu.lanling.event.camera.TinyVideoCaptureEvent
import com.xiaoyu.lanling.util.ImageFileCompressUtils
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_camera.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class CameraActivity : AppCompatToolbarActivity() {

    private var compressImageDisposable: Disposable? = null

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        hideSystemUI()
        setContentView(R.layout.activity_camera)
        initBind()
    }

    private fun initBind() {
        val mediaDir = externalMediaDirs.first { it.exists() }
                ?: Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
        camera_view.setSaveVideoPath(mediaDir.absolutePath)

        camera_view.setLeftClickListener { finish() }
        camera_view.setRightClickListener { camera_view.switchCamera() }
        camera_view.setJCameraListener(object : JCameraListener {
            override fun recordSuccess(videoOutputFilePath: String, firstFrame: Bitmap) {
                mediaScanAndSend(videoOutputFilePath)
            }

            override fun captureSuccess(bitmap: Bitmap?) {
                compressImageDisposable = ImageFileCompressUtils.createFileForBitmap(bitmap, createFile(this@CameraActivity, "jpg"))
                        .compose(RxUtils.ioToMainSingleScheduler<File>())
                        .subscribe { file ->
                            ImageCaptureEvent(file.absolutePath).post()
                            finish()
                        }
            }
        })
    }

    private fun mediaScanAndSend(videoOutputFilePath: String) {
        MediaScannerConnection.scanFile(
                applicationContext, arrayOf(videoOutputFilePath), null) { path, uri ->
            val projection = arrayOf("duration")
            val cursor = MediaStore.Video.query(contentResolver, uri, projection)
                    ?: return@scanFile
            if (cursor.moveToFirst()) {
                val duration = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION))
                // 四舍五入
                val correctedDuration = (duration / 1000 + if (duration % 1000 >= 500) 1 else 0) * 1000
                TinyVideoCaptureEvent(videoOutputFilePath, correctedDuration).post()
            }
            if (cursor.isClosed.not()) {
                cursor.close()
            }
            finish()
        }
    }

    private fun hideSystemUI() {
        val decorView = window.decorView
        val uiOptions = (View.SYSTEM_UI_FLAG_IMMERSIVE
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar
                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN)
        decorView.systemUiVisibility = uiOptions
    }

    override fun onDestroy() {
        super.onDestroy()
        camera_view.release()
        RxUtils.disposable(compressImageDisposable)
    }

    companion object {
        private val TAG = CameraActivity::class.java.simpleName

        private fun createFile(context: Context, extension: String): File {
            val sdf = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS", Locale.US)
            val mediaDir = context.externalMediaDirs.first { it.exists() }
                    ?: Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            return File(mediaDir, "VID_${sdf.format(Date())}.$extension")
        }
    }
}